package com.mt.skyhoist.ui.activity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;


import com.mt.skyhoist.util.GlobalVariable;
import com.mt.skyhoist.util.bean.DeviceModel;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.model.ErroCode;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class ScanDeviceService extends Service {
    public static final int StartScan = 1;
    public static final int StopScan = 2;
    public static final int Refresh = 3;
    public static final int SelectedChange = 4;

    public ScanDeviceService() {
    }

    private GlobalVariable mGlobalVariable;

    @Override
    public void onCreate() {
        super.onCreate();
        mGlobalVariable = GlobalVariable.getinstance();

        initBLE();

//        onMessageEvent(StartScan);
    }

    private MTBLEManager manger;

    private void initBLE() {
        this.manger = MTBLEManager.getInstance(getApplicationContext());
        EventBus.getDefault().register(this);
    }

    private boolean scanStatus = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Integer event) {
        switch (event) {
            case StartScan:
                if (scanStatus) {
                    return;
                }
                scanStatus = true;
                handler.sendEmptyMessageDelayed(RefreshEvent, 2000);

//                for (int i=0; i< 10; i++){
//                    DeviceModel device = new DeviceModel(null, "11:11:11:11", "test1", -1);
////                    mGlobalVariable.getFreeDeviceList().add(device);
//                    mGlobalVariable.getDeviceGroup().get(i).add(device);
//                }

//                mGlobalVariable.getFreeDeviceList().add(new DeviceModel(null, "11:11:11:11", "test1", -1));
//                mGlobalVariable.getFreeDeviceList().add(new DeviceModel(null, "11:11:11:11", "test2", -1));
//                mGlobalVariable.getFreeDeviceList().add(new DeviceModel(null, "11:11:11:11", "test3", -1));
//
//                mGlobalVariable.getFreeDeviceList().get(0).setRssi(-40);
//                mGlobalVariable.getFreeDeviceList().get(2).setRssi(-40);

                manger.startScan(MTBLEManager.ScanMode.FAST, null, scanCallback, 5, 1, 0);
                break;
            case StopScan:
                if (!scanStatus) {
                    return;
                }
                scanStatus = false;
                handler.removeMessages(RefreshEvent);
                manger.stopScan();
                break;
        }
    }

    // 2秒刷新一次扫描结果
    private final int RefreshEvent = 4;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EventBus.getDefault().post(Refresh);
            handler.sendEmptyMessageDelayed(RefreshEvent, 2000);
        }
    };

    private MTBLEManager.MTScanCallback scanCallback = new MTBLEManager.MTScanCallback() {

        @Override
        public void onScanFail(int errocode, String erromsg) {

        }

        @SuppressLint("MissingPermission")
        @Override
        public void onScan(MTBLEDevice device) {
            if (device.getDevicetype() != MTBLEDevice.MTBLEDEVICETYPE.MTBLE) {
                return;
            }

            for (DeviceModel i : mGlobalVariable.getDeviceList()) {   // 设备被绑定过
                if (i.getMac().equals(device.getDevice().getAddress())) {
                    i.setRssi(device.getAvgRssi());
                    i.setName(device.getDevice().getName());
                    return;
                }
            }

            for (DeviceModel i : mGlobalVariable.getFreeDeviceList()) {  // 设备没被绑定过，更新
                if (i.getMac().equals(device.getDevice().getAddress())) {
                    i.setRssi(device.getAvgRssi());
                    i.setName(device.getDevice().getName());
                    return;
                }
            }

            DeviceModel d = new DeviceModel(null, device.getDevice().getAddress(),
                    device.getDevice().getName(), 0);
            d.setRssi(device.getAvgRssi());
            mGlobalVariable.getFreeDeviceList().add(d);
        }

        @Override
        public void onScanOver(ErroCode errocode) {

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
